var VSHADER_SOURCE = 

//x' = x cos b - y sin b 
//y' = x sin b + y cos b
//z' = z  
	'attribute vec4 a_Position;\n'+
	'uniform mat4 u_ModleMatrix;\n'+
	'void main(){\n'+
	'   gl_Position = u_ModleMatrix * a_Position ;\n'+
	'}\n';
	
var FSHADER_SOURCE =
	'void main(){\n'+
	'gl_FragColor = vec4(1.0 , 0.0 , 0.0 , 1.0 );\n'+
	'}\n';


	//在x，y ， z方向上平移的距离
var ANGLE_STEP = 245.0 ;

function main(){
	var canvas = document.getElementById('webgl');
	var gl = getWebGLContext(canvas) ;
	if(!gl){
		console.log('...');
		return 
	}
	
	if(!initShaders(gl , VSHADER_SOURCE , FSHADER_SOURCE)){
		console.log('111111');
		return 
	}
	
	var n = initVertexBuffers(gl);
	//判断n是否是小于0
	if(n<0){
		console.log('.....');
		return 
	}

	gl.clearColor(0.8 , 0.8 , 0.8 , 1.0 );
	
    var u_ModleMatrix = gl.getUniformLocation(gl.program , 'u_ModleMatrix');

    var currentAngle = 0.0 ;

    var modleMatrix = new Matrix4() ;

    //开始绘制三角形
    var tick = function(){
        currentAngle = animate(currentAngle) ; //更新旋转角
        draw(gl , n , currentAngle , modleMatrix , u_ModleMatrix);
        requestAnimationFrame(tick) ;
    };

    tick() ;
	
}

function initVertexBuffers(gl){
	var vertices = new Float32Array([
		-0.5 , 0.5 , -0.5 , -0.5 , 0.5 ,-0.5 /*, 0.5 , 0.5*/ 
	]);
	
	var n = 3 ;
	
	//创建缓冲区对象
	var vertexBuffer = gl.createBuffer();
	if(!vertexBuffer){
		console.log(',,,');
		return -1 ;
	}
	
	//绑定缓冲区对象
	gl.bindBuffer(gl.ARRAY_BUFFER , vertexBuffer);
	
	//向缓冲区对象写入数据
	gl.bufferData(gl.ARRAY_BUFFER , vertices , gl.STATIC_DRAW) ;
	
	var a_Position = gl.getAttribLocation(gl.program , 'a_Position');
	if(a_Position<0){
		console.log('.....');
		return
	}
	
	//将缓冲区对象分配给a_Position变量(attribute)
	gl.vertexAttribPointer(a_Position , 2 ,gl.FLOAT , false , 0 , 0) ;
	
	//连接a_Position变量（attribute）与分配给它的缓冲区对象
	gl.enableVertexAttribArray(a_Position);
	
	return n ;
}

function draw(gl , n , currentAngle , modleMatrix ,u_ModleMatrix){
    //设置旋转矩阵
    modleMatrix.setRotate(currentAngle , 0 , 0 , 1) ;

    //将旋转矩阵传输给顶点着色器
    gl.uniformMatrix4fv(u_ModleMatrix , false , modleMatrix.elements) ;

    //清除<canvas>
    gl.clear(gl.COLOR_BUFFER_BIT);
    gl.drawArrays(gl.TRIANGLES , 0 , n);
}

var g_last = Date.now() ;
function animate(angle){

    //计算距离上次调用经过多长时间
    var now = Date.now() ;
    var elapsed = now - g_last ; //毫秒
    g_last = now ;

    //根据距离上次调用的时间 ，更新当前的旋转角度
    var newAngle = angle + (ANGLE_STEP * elapsed)/1000.0 ;
    return newAngle %= 360 ;
}

function changeDir(){
    ANGLE_STEP *= -1 ;
}